import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:get/get.dart';

import '../../../bean/bean_order.dart';
import 'controller/order_manager_center_controller.dart';

class OrderManagerListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return OrderListPageState();
  }
}

class OrderListPageState extends State with SingleTickerProviderStateMixin {
  TabController _tabController;
  ScrollController _scrollController = new ScrollController();

  @override
  void initState() {
    super.initState();
    Get.put(OrderManagerCenterController());
    _tabController = new TabController(length: 3, vsync: this);
    _scrollController.addListener(() {
      double offset = _scrollController.offset;
      double maxOfsset = _scrollController.position.maxScrollExtent;
      if (offset > maxOfsset / 3 * 2) {
        Get.find<OrderManagerCenterController>().loadingMore();
      }
    });

    Future.delayed(Duration.zero, () {
      Get.find<OrderManagerCenterController>().initLonding();
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      id: "orderList",
      builder: (OrderManagerCenterController controller) {
        int allCount = controller.allCount;
        int sendCount = controller.sendCount;
        int finishCount = controller.finishCount;

        return Scaffold(
          appBar: AppBar(
            leading: BackButton(
              onPressed: () => Get.back(),
            ),
            title: Text("管理订单中心"),
            elevation: 0,
            bottom: TabBar(
              indicatorColor: Colors.red,
              controller: _tabController,
              onTap: (int index) {
                Get.find<OrderManagerCenterController>()
                    .onRefresh(index: index);
              },
              tabs: [
                Tab(text: '全部($allCount)'),
                Tab(text: '待收货($sendCount)'),
                Tab(text: '已完成($finishCount)'),
              ],
            ),
            actions: [
              Builder(builder: (BuildContext context) {
                return TextButton(
                    onPressed: () {
                      Scaffold.of(context).openEndDrawer();
                    },
                    child: Text("筛选"));
              })
            ],
          ),
          endDrawer: buildEndDrawer(),
          body: RefreshIndicator(
            onRefresh: () {
              return Get.find<OrderManagerCenterController>().onPullRefresh();
            },
            child: bildMainWidget(controller),
          ),
        );
      },
    );
  }

  Widget buildCodeTipsRow(int orderStatues, OrderBean item) {
    if (item.orderStatues == 401 || item.orderStatues == 402) {
      return Container();
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Expanded(
          child: Text(
            "请向取货用户核对取货码",
            textAlign: TextAlign.start,
            style: TextStyle(
                fontSize: 16, color: Colors.black, fontWeight: FontWeight.w500),
          ),
        ),
        GetBuilder(
          id: "sendshop",
          builder: (OrderManagerCenterController controller) {
            if (controller.sendLoading) {
              return LoadingWidget(
                text: "处理中",
              );
            }
            return buildSendShopButton(orderStatues, item);
          },
        ),
      ],
    );
  }

  Widget buildSendShopButton(int orderStatues, OrderBean item) {
    if (orderStatues == 401 || orderStatues == 402) {
      return Container();
    }

    if (orderStatues == 201) {
      return GestureDetector(
        onTap: () {
          Get.find<OrderManagerCenterController>().confirm(item);
        },
        child: ClipRRect(
          child: Container(
            padding: EdgeInsets.only(left: 12, right: 12, top: 8, bottom: 8),
            color: Colors.red[900],
            child: Text(
              "发货",
              style: TextStyle(
                  fontSize: 12,
                  color: Colors.white,
                  fontWeight: FontWeight.w600),
            ),
          ),
          borderRadius: BorderRadius.all(Radius.circular(4)),
        ),
      );
    }
    return Container();
  }

  buildUsedTimeWidget(OrderBean item) {
    if (item.orderStatues != 401 && item.orderStatues != 402) {
      return Container();
    }
    return Container(
      margin: EdgeInsets.only(top: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text(
            "取货时间 ${item.confirmTime}",
            textAlign: TextAlign.end,
            style: TextStyle(fontSize: 14, color: Colors.black),
          )
        ],
      ),
    );
  }

  TextEditingController _nameController = new TextEditingController();
  TextEditingController _snController = new TextEditingController();

  buildEndDrawer() {
    return Container(
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        child: Container(
          padding: EdgeInsets.only(left: 20, right: 20, bottom: 20, top: 20),
          width: 300,
          height: 260,
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    "筛选条件",
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              TextField(
                controller: _nameController,
                decoration: InputDecoration(hintText: "请输入用户姓名 "),
              ),
              SizedBox(
                height: 8,
              ),
              TextField(
                controller: _snController,
                decoration: InputDecoration(hintText: "请输入订单编号 "),
              ),
              SizedBox(
                height: 28,
              ),
              Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      String userName = _nameController.text;
                      String sn = _snController.text;
                      _tabController.animateTo(0);
                      Get.find<OrderManagerCenterController>()
                          .onSerach(userName: userName, orderSn: sn);
                      Navigator.pop(context);
                    },
                    child: ClipRRect(
                      child: Container(
                        padding: EdgeInsets.only(
                            left: 12, right: 12, top: 8, bottom: 8),
                        color: Colors.red[900],
                        child: Text(
                          "搜索",
                          style: TextStyle(
                              fontSize: 12,
                              color: Colors.white,
                              fontWeight: FontWeight.w600),
                        ),
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(4)),
                    ),
                  )
                ],
                mainAxisAlignment: MainAxisAlignment.end,
              )
            ],
          ),
        ),
      ),
    );
  }

  bildMainWidget(OrderManagerCenterController controller) {
    if (controller.loadingList) {
      return LoadingWidget();
    }
    List<OrderBean> goodsList = controller.orderList;
    if (goodsList.length == 0) {
      return Container(
        height: double.infinity,
        child: NoDataWidget(
          text: "暂无订单",
        ),
      );
    }
    return ListView.builder(
      controller: _scrollController,
      itemCount: goodsList.length,
      itemBuilder: (BuildContext context, int index) {
        OrderBean item = goodsList[index];

        int orderStatues = item.orderStatues;
        String orderStatuesStr = "未知";
        Color orderStatuesColor = Colors.grey;
        if (orderStatues == 201) {
          orderStatuesStr = "待取货 ";
          orderStatuesColor = Colors.red[800];
        } else if (orderStatues == 401) {
          orderStatuesStr = "已取货 ";
          orderStatuesColor = Colors.grey;
        } else if (orderStatues == 402) {
          orderStatuesStr = "已取货 ";
          orderStatuesColor = Colors.grey;
        }

        return Container(
          color: Colors.white,
          margin: EdgeInsets.only(top: 1),
          padding: EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 2),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      "订单编号 ${item.orderSn}",
                      style:
                      TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                    ),
                  ),
                  Text(
                    "$orderStatuesStr",
                    style: TextStyle(
                        fontSize: 14,
                        color: orderStatuesColor,
                        fontWeight: FontWeight.w500),
                  )
                ],
              ),
              SizedBox(
                height: 4,
              ),
              Container(
                padding:
                EdgeInsets.only(left: 12, top: 8, right: 12, bottom: 8),
                decoration: BoxDecoration(
                    color: Color(0xffeeeeee),
                    borderRadius: BorderRadius.all(Radius.circular(4))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "下单用户信息",
                      style: TextStyle(fontSize: 12, color: Colors.black),
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Text(
                      "用户名：${item.userName}  电话：${item.userPhone}",
                      style: TextStyle(fontSize: 12, color: Colors.black),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 8,
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  CachedNetworkImage(
                    imageUrl: item.goodsImage,
                    width: 40,
                  ),
                  SizedBox(width: 6),
                  Expanded(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          item.goodsName,
                          style: TextStyle(fontSize: 14, color: Colors.grey),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Text(
                              "单价 ${item.unitNumber} 积分",
                              textAlign: TextAlign.end,
                              style:
                              TextStyle(fontSize: 14, color: Colors.grey),
                            )
                          ],
                        ),
                        SizedBox(
                          height: 6,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Text(
                              "订单总价 ${item.orderPrice} 积分",
                              textAlign: TextAlign.end,
                              style:
                              TextStyle(fontSize: 14, color: Colors.grey),
                            )
                          ],
                        )
                      ],
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 6,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(
                    "下单时间 ${item.createTime}",
                    textAlign: TextAlign.end,
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  )
                ],
              ),
              buildUsedTimeWidget(item),
              orderStatues == 201 ? Divider() : SizedBox(),
              buildCodeTipsRow(orderStatues, item),
              SizedBox(
                height: 6,
              ),
            ],
          ),
        );
      },
    );
  }
}
